package com.lanxi.nbpaytest.Controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.lanxi.nbpaytest.Service.MailService;
import com.lanxi.nbpaytest.Service.PayService;
import com.lanxi.nbpaytest.TimeUtil;
import com.lanxi.nbpaytest.requestparam.AccountRequest;
import com.lanxi.nbpaytest.requestparam.QueryBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author mintaoyu
 * Date on 2020-03-13  10:19
 *
 * 对账文件下载
 */

@Slf4j
@RestController
public class AccountController {

    @Autowired
    PayService payService;

    @Autowired
    MailService mailService;

    @Value("${lx.mailOne}")
    private String mailOne;

    @Value("${lx.mailTwo}")
    private String mailTwo;

    @Value("${lx.mailThree}")
    private String mailThree;

    @Value("${lanxi.appid}")
    private String appId;


    /**
     * @param billDate 下载对账单的日期 yyyyMMdd 20200312
     * @param 商户号      333021258121280  正式 313331090089000
     */
    @GetMapping("/downloadAccount")
    public void downloadAccount(String billDate, HttpServletResponse response) throws UnsupportedEncodingException {
        if (billDate.contains("-")) {
            billDate = billDate.replaceAll("-", "");
        }
        QueryBody queryBody = new QueryBody();
        AccountRequest request = new AccountRequest();
        request.setBillDate(billDate);
        request.setMerId("313331090089000");
        String body = JSON.toJSONString(request);
        payService.formalInit();
        String signMsg = payService.sign(body);
        queryBody.setBody(body);
        queryBody.setSignMsg(signMsg);
        String querybodyJSON = JSON.toJSONString(queryBody);
        log.info("下载body" + querybodyJSON);
        List<ArrayList<String>> rows = payService.myPost(appId, "https://aapw.nbcb.com.cn/pay/api/v1/checkingFile/download", querybodyJSON);
        //通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter();
        //一次性写出内容，强制输出标题
        writer.write(rows, true);
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + billDate + URLEncoder.encode("对账单", "UTF-8") + ".xls");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.flush(out, true);
// 关闭writer，释放内存
        writer.close();
//此处记得关闭输出Servlet流
        IoUtil.close(out);
    }

    /**
     * 定时推送到指定邮箱
     *
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/pushAccount")
    public void pushAccount() throws UnsupportedEncodingException {
        // 获取当天日期
        String billDate = TimeUtil.getDate();
        QueryBody queryBody = new QueryBody();
        AccountRequest request = new AccountRequest();
        request.setBillDate(billDate);
        request.setMerId("313331090089000");
        String body = JSON.toJSONString(request);
        payService.init();
        String signMsg = payService.sign(body);
        queryBody.setBody(body);
        queryBody.setSignMsg(signMsg);
        String querybodyJSON = JSON.toJSONString(queryBody);
        log.info("下载body" + querybodyJSON);
        List<ArrayList<String>> rows = payService.myPost(appId, "https://aapw.nbcb.com.cn/pay/api/v1/checkingFile/download", querybodyJSON);
        //通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter();
        //一次性写出内容，强制输出标题
        writer.write(rows, true);
        // 输出地址
        writer.setDestFile(new File("/home/" + billDate + "对账单.xlsx"));
        writer.flush();
        // 关闭writer，释放内存
        writer.close();
        // 将邮件推送
        mailService.sendAttachmentsMail("690486631@qq.com", billDate + "对账单.xlsx", "对账单", "/home/" + billDate + "对账单.xlsx");
    }


    @PostMapping("/reciveExcel")
    public void reciveExcel(HttpServletResponse response, HttpServletRequest request, MultipartFile file) {
        try {
            InputStream fileInputStream = file != null ? file.getInputStream() : null;
            FileOutputStream out = new FileOutputStream(new File("test.xls"));
            byte[] bs = new byte[1024];
            int len;
            while ((len = fileInputStream != null ? fileInputStream.read(bs) : 0) != -1) {
                out.write(bs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println();
    }

    @RequestMapping("/test")
    public void test(HttpServletRequest request, HttpServletResponse response) {
        String dataContent = request.getParameter("dataContent");
        System.out.println(dataContent);
    }
}
